package com.scalar.chiptrack.adaptor.analogix;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.InventoryLot;
import com.scalar.chiptrack.adaptor.FabSortLot;
import com.scalar.chiptrack.adaptor.AssemblyLot;
import com.scalar.chiptrack.adaptor.TestLot;
import com.scalar.chiptrack.adaptor.ShippedLot;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.XLSParserImpl;
import com.scalar.chiptrack.adaptor.utac.UTACPOP3Adaptor;
import com.scalar.chiptrack.adaptor.dao.AssemblyAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.TestAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.InventoryLotDAO;
import com.scalar.chiptrack.adaptor.dao.FabSortAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.ScalarException;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.Locale;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import jxl.Sheet;
import jxl.Workbook;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 15 Dec, 2010
 * Time: 11:57:57 AM
 * To change this template use File | Settings | File Templates.
 */
public class UTACDataParser extends JobHandler implements AdaptorConstants
{
    private static Logger m_parserLogger    = null;
    private String m_dataOutputDir          = null;

    private HashMap<String, AssemblyLot> m_assyUSCWipDataMap    = new HashMap<String, AssemblyLot>();
    private HashMap<String, AssemblyLot> m_assyUSGWipDataMap    = new HashMap<String, AssemblyLot>();
    private HashMap<String, TestLot> m_ftUSCDataMap             = new HashMap<String, TestLot>();
    private HashMap<String, TestLot> m_ftUSGDataMap             = new HashMap<String, TestLot>();
    private HashMap<String, InventoryLot> m_dieBankUSCDataMap   = new HashMap<String, InventoryLot>();
    private HashMap<String, InventoryLot> m_dieBankUSGDataMap   = new HashMap<String, InventoryLot>();
    private HashMap<String, InventoryLot> m_fgUSCDataMap        = new HashMap<String, InventoryLot>();
    private HashMap<String, InventoryLot> m_fgUSGDataMap        = new HashMap<String, InventoryLot>();

    public UTACDataParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = AdaptorUtils.getDataOutputDir( VENDOR_NAME_UTAC, WIP_TYPE_ASSEMBLY );
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_parserLogger = AdaptorUtils.getDataParserLogger( m_dataOutputDir,VENDOR_NAME_UTAC );
            AssemblyAdaptorDAO.setLogger( m_parserLogger );   // All the DAOs and Parser should be logging into same file
            TestAdaptorDAO.setLogger( m_parserLogger);
            InventoryLotDAO.setLogger( m_parserLogger );
            AdaptorUtils.setLogger( m_parserLogger );
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading/creating UTAC output directory from database, Exception: " + se);
            throw se;
        }
    }
    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main( String args[] ) throws Exception
    {
        try
        {
            new UTACDataParser().execute();
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    //Execute Method
   public void execute() throws Exception
   {
       AdaptorUtils.printHeader(VENDOR_NAME_UTAC, CONSTANT_PARSER );

       File doneDestDir = new File( m_dataOutputDir + "/done" );

       File wipDataoutDir = new File( m_dataOutputDir );

       File[] fileList = wipDataoutDir.listFiles();

       if ( ( fileList == null ) || ( fileList.length <= 3 ) )
       {
           log( "No file found in directory: " + wipDataoutDir );
           throw new ScalarException( "No file found in directory: " + wipDataoutDir + "----\n\n" );
       }

       DBTransaction dbTransaction = null;
       ArrayList<File> successFileList   = new ArrayList<File>();
       boolean success  = false;

       try
       {
           for ( int i = 0; i < fileList.length; i++ )
           {
               if ( fileList[i].isDirectory() == true )
               {
                   continue;
               }

               if ( ( fileList[i].getName() != null ) && ( fileList[i].getName().trim().indexOf( UTACPOP3Adaptor.FILE_NAME_SG_WIP ) != -1 ) )
               {
                    parseDailyUSGWipReport( fileList[i].getAbsolutePath() );

                    successFileList.add( fileList[i] );
               }
               if ( ( fileList[i].getName() != null ) && ( fileList[i].getName().trim().indexOf( UTACPOP3Adaptor.FILE_NAME_SC_WIP ) != -1 ) )
               {
                    parseDailyUSCWipReport( fileList[i].getAbsolutePath() );

                    successFileList.add( fileList[i] );
               }
           }
       }
       catch ( Exception e )
       {
           success = false;
           log( "ERROR!! ERROR!! ERROR!! While parsing and storing File " + e );
           e.printStackTrace();
           throw e;
       }

       // to save the Die Bank lot tables
       try
       {
           if ( m_dieBankUSGDataMap.isEmpty() == false )
           {
               log(" Updating Die Bank Lot Information");
               InventoryLotDAO.saveInventoryLot( dbTransaction/*null*/, m_dieBankUSGDataMap.values().iterator(), INVENTORY_TYPE_DIE_BANK, VENDOR_NAME_UTAC );
               success = true;
           }
           else
           {
               InventoryLotDAO.closeInventoryLot(dbTransaction/*null*/, INVENTORY_TYPE_DIE_BANK, VENDOR_NAME_UTAC  );
           }
           if ( m_dieBankUSCDataMap.isEmpty() == false )
           {
               log(" Updating Die Bank Lot Information");
               InventoryLotDAO.saveInventoryLot( dbTransaction/*null*/, m_dieBankUSCDataMap.values().iterator(), INVENTORY_TYPE_DIE_BANK, VENDOR_NAME_UTAC_SH );
               success = true;
           }
           else
           {
               InventoryLotDAO.closeInventoryLot(dbTransaction/*null*/, INVENTORY_TYPE_DIE_BANK, VENDOR_NAME_UTAC_SH  );
           }
      }
      catch (ScalarException se)
      {
          success = false;
          se.printStackTrace();
          log("ERROR!! ERROR!! ERROR!! Could not update DieBank Lot information into database: " + se);
          throw se;
      }

       // to save the Assembly lot tables
       try
       {
           if ( m_assyUSGWipDataMap.isEmpty() == false )
           {
               log(" Updating Assembly Lot Information");
               AssemblyAdaptorDAO.saveAssemblyLot( dbTransaction/*null*/, m_assyUSGWipDataMap.values().iterator(), WIP_TYPE_ASSEMBLY, VENDOR_NAME_UTAC );
               success = true;
           }
           else
           {
               AssemblyAdaptorDAO.closeAssemblyLot(dbTransaction, WIP_TYPE_ASSEMBLY, VENDOR_NAME_UTAC );
           }
           if ( m_assyUSCWipDataMap.isEmpty() == false )
           {
               log(" Updating Assembly Lot Information");
               AssemblyAdaptorDAO.saveAssemblyLot( dbTransaction/*null*/, m_assyUSCWipDataMap.values().iterator(), WIP_TYPE_ASSEMBLY, VENDOR_NAME_UTAC_SH );
               success = true;
           }
           else
           {
               AssemblyAdaptorDAO.closeAssemblyLot(dbTransaction, WIP_TYPE_ASSEMBLY, VENDOR_NAME_UTAC_SH );
           }
      }
      catch (ScalarException se)
      {
          success = false;
          se.printStackTrace();
          log("ERROR!! ERROR!! ERROR!! Could not update Assembly Lot information into database: " + se);
          throw se;
      }

      /*Updating the Test Lot Information*/
      try
      {
          // Save Test Information
          if( m_ftUSGDataMap.isEmpty() == false )
          {
              log(" Updating Test Lot Information");
              TestAdaptorDAO.saveTestLot( dbTransaction/*null*/, m_ftUSGDataMap.values().iterator(), LOCATION_TYPE_FT, VENDOR_NAME_UTAC );
              success = true;
          }
          else
          {
              TestAdaptorDAO.closeTestLot( dbTransaction, LOCATION_TYPE_FT, VENDOR_NAME_UTAC );
          }

          if( m_ftUSCDataMap.isEmpty() == false )
          {
              log(" Updating Test Lot Information");
              TestAdaptorDAO.saveTestLot( dbTransaction/*null*/, m_ftUSCDataMap.values().iterator(), LOCATION_TYPE_FT, VENDOR_NAME_UTAC_SH );
              success = true;
          }
          else
          {
              TestAdaptorDAO.closeTestLot( dbTransaction, LOCATION_TYPE_FT, VENDOR_NAME_UTAC_SH );
          }
      }
      catch (ScalarException se)
      {
          success = false;
          se.printStackTrace();
          log("ERROR!! ERROR!! ERROR!! Could not update Test Lot information into database: " + se);
          throw se;
      }

      // to save the FG lot tables
      try
      {
           if ( m_fgUSGDataMap.isEmpty() == false )
           {
               log(" Updating Finshed Goods Lot Information");
               InventoryLotDAO.saveInventoryLot( dbTransaction/*null*/, m_fgUSGDataMap.values().iterator(), LOCATION_TYPE_FG, VENDOR_NAME_UTAC );
               success = true;
           }
           else
           {
               InventoryLotDAO.closeInventoryLot(dbTransaction/*null*/, LOCATION_TYPE_FG, VENDOR_NAME_UTAC  );
           }
           if ( m_fgUSCDataMap.isEmpty() == false )
           {
               log(" Updating Finshed Goods Lot Information");
               InventoryLotDAO.saveInventoryLot( dbTransaction/*null*/, m_fgUSCDataMap.values().iterator(), LOCATION_TYPE_FG, VENDOR_NAME_UTAC_SH );
               success = true;
           }
           else
           {
               InventoryLotDAO.closeInventoryLot(dbTransaction/*null*/, LOCATION_TYPE_FG, VENDOR_NAME_UTAC_SH  );
           }
      }
      catch (ScalarException se)
      {
          success = false;
          se.printStackTrace();
          log("ERROR!! ERROR!! ERROR!! Could not update Finshed Goods Lot information into database: " + se);
          throw se;
      }

       // To Close the Drop Out Lots
      AdaptorDAO.closeDropOutLots( VENDOR_NAME_UTAC );
      AdaptorDAO.closeDropOutLots( VENDOR_NAME_UTAC_SH );

      // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
      AdaptorDAO.sendAllNotifications( VENDOR_NAME_UTAC, true, true, true );
      AdaptorDAO.sendAllNotifications( VENDOR_NAME_UTAC_SH, true, true, true );

      int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( UTACPOP3Adaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);

      // Update Adaptor_Run_Info table
      try
      {
            if ( success == true )
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, UTACPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
            }
      }
      catch ( ScalarException se )
      {
            success = false; //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, UTACPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
            throw se;
       }
        // Move the successful files to 'done' directory
       if ( success )
       {
           AdaptorUtils.moveFilesToDone( successFileList, doneDestDir );
       }
   }//end of execute method

   private void parseDailyUSCWipReport(String fileName) throws Exception
   {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result        = null;
        AssemblyLot  assemblyLot   = null;
        InventoryLot inventoryLot  = null;
        TestLot      testLot       = null;

        try
        {
            File detailWipFile = new File( fileName );
            if ( !detailWipFile.exists() )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "\nParsing the file for USC Wip Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for USC Wip Report..." );

            Parser parser = ParserFactory.getXLSParser( detailWipFile );

            ArrayList sheetNamesList = ((XLSParserImpl)parser).getSheetNamesList();

            for(int i= 0; i< sheetNamesList.size(); i++ )
            {
                String partNumber       = null;
                String fabLotNumber     = null;
                String lotNumber        = null;
                
                String sheetName = (String)sheetNamesList.get( i );

                ((XLSParserImpl)parser).setHeaderRowIdx(4);
                ((XLSParserImpl)parser).setDataStartRowIdx(5);

                result = ((XLSParserImpl)parser).parse( sheetName );
                //System.out.println("sheetName = " + sheetName);
                while ( result.next() )
                {
                    partNumber = result.getString("Customer Device");
                    fabLotNumber = result.getString("Customer Lotid");
                    lotNumber = result.getString("Utac Lotid");

                    String lotStatus    = null;
                    String lotCategory  = null;
                    String dateIn       = null;
                    if ( result.getString("Lot Type") != null && "EL".equalsIgnoreCase(result.getString("Lot Type") ) )
                    {
                         lotCategory = LOT_CATEGORY_TYPE_ENGG;
                    }
                    else
                    {
                        lotCategory = LOT_CATEGORY_TYPE_PROD;
                    }
                    if (result.getString("State") != null && ( "HELD".equalsIgnoreCase(result.getString("State") ) || result.getString("State").indexOf("HLD") != -1 ) )
                    {
                        lotStatus = LOT_STATUS_HOLD;
                    }
                    else
                    {
                       lotStatus = LOT_STATUS_RUNNING;
                    }
                    dateIn = DateUtil.getPreviousDate( result.getInt("Lot Age"), "MM/dd/yyyy");

                    if ( partNumber != null && partNumber.trim().length() > 0 && lotNumber != null && lotNumber.trim().length() >0 )
                    {
                        if ( sheetName != null && ( sheetName.toUpperCase().equalsIgnoreCase("ASSY") || sheetName.toUpperCase().equalsIgnoreCase("ASSEMBLY") ) )
                        {
                            if ( result.getString("Stage") != null && "P200-DBANK".equalsIgnoreCase(result.getString("Stage").toUpperCase() ) )
                            {
                                inventoryLot = (InventoryLot)m_dieBankUSCDataMap.get( partNumber + fabLotNumber );
                                if ( inventoryLot == null )
                                {
                                    inventoryLot = new InventoryLot( VENDOR_NAME_UTAC_SH, LOCATION_TYPE_DIE_BANK );
                                    m_dieBankUSCDataMap.put( partNumber + fabLotNumber, inventoryLot );
                                }
                                int quantity = 0;
                                int wquantity = 0;
                                if (inventoryLot.getQtyIn() != null)
                                {
                                    try
                                    {
                                        quantity = Integer.parseInt(inventoryLot.getQtyIn());
                                        wquantity = Integer.parseInt(inventoryLot.getWaferQtyIn());
                                    }
                                    catch (NumberFormatException ignore) {
                                    }
                                    quantity += result.getInt("Subqty");
                                    wquantity += result.getInt("Qty");
                                }
                                else
                                {
                                    quantity = result.getInt("Subqty");
                                    wquantity = result.getInt("Qty");
                                }


                                if (quantity > 0 )
                                {
                                    inventoryLot.setPartNumber( partNumber );
                                    inventoryLot.setLotNumber( fabLotNumber );
                                    inventoryLot.setQtyIn(quantity + "");
                                    inventoryLot.setWaferQtyIn( wquantity + "");
                                    inventoryLot.setDateIn( dateIn );
                                    inventoryLot.setFabLotNumber( fabLotNumber );
                                    inventoryLot.setStatus( lotStatus );
                                    inventoryLot.setLotCategory( lotCategory );
                                }
                            }//End OF Die Bank
                            else
                            {
                                assemblyLot = (AssemblyLot) m_assyUSCWipDataMap.get( partNumber + lotNumber + fabLotNumber );
                                if (assemblyLot == null)
                                {
                                    assemblyLot = new AssemblyLot( VENDOR_NAME_UTAC_SH, WIP_TYPE_ASSEMBLY );
                                    m_assyUSCWipDataMap.put( partNumber + lotNumber + fabLotNumber, assemblyLot);
                                }
                                int quantity = 0;
                                if (assemblyLot.getQtyIn() != null)
                                {
                                    try
                                    {
                                        quantity = Integer.parseInt(assemblyLot.getQtyIn());
                                    }
                                    catch (NumberFormatException ignore) {
                                    }
                                    quantity += result.getInt("Subqty");
                                }
                                else
                                {
                                    quantity = result.getInt("Subqty");
                                }

                                if ( quantity > 0 )
                                {
                                    assemblyLot.setLotNumber( lotNumber );
                                    assemblyLot.setDeviceName( partNumber );
                                    assemblyLot.setStatus(lotStatus);
                                    assemblyLot.setFabLotNumber( fabLotNumber );
                                    assemblyLot.setCategory( lotCategory );
                                    assemblyLot.setDateIn( dateIn );
                                    assemblyLot.setStage( result.getString("Stage"));
                                    assemblyLot.setQtyIn( quantity+"" );
                                }
                            }
                        } //End Of ASSY Sheet
                        //TEST
                        if ( sheetName != null && sheetName.toUpperCase().equalsIgnoreCase("TEST")  )
                        {
                            testLot = (TestLot) m_ftUSCDataMap.get( partNumber + lotNumber + fabLotNumber );
                            if (testLot == null)
                            {
                                testLot = new TestLot( VENDOR_NAME_UTAC_SH, LOCATION_TYPE_FT );
                                m_ftUSCDataMap.put(partNumber + lotNumber + fabLotNumber, testLot);
                            }

                            int quantity = 0;
                            if (testLot.getQtyIn() != null)
                            {
                                try
                                {
                                    quantity = Integer.parseInt(testLot.getQtyIn());
                                }
                                catch (NumberFormatException ignore) {
                                }
                                quantity += result.getInt("Qty");
                            }
                            else
                            {
                                quantity = result.getInt("Qty");
                            }

                            if ( quantity > 0 )
                            {
                                testLot.setPartNumber( partNumber );
                                testLot.setLotNumber( lotNumber );
                                testLot.setFabLotNumber( fabLotNumber );
                                testLot.setDateIn( dateIn );
                                testLot.setStage( result.getString("Stage") );
                                testLot.setQtyIn( quantity + "");
                                testLot.setStatus(lotStatus);
                                testLot.setCategory( lotCategory );
                            }
                        }//End OF TEST

                        //FG
                        if ( sheetName != null && (sheetName.toUpperCase().equalsIgnoreCase("PTC") || sheetName.toUpperCase().equalsIgnoreCase("EOL") ) )
                        {
                            inventoryLot = (InventoryLot) m_fgUSCDataMap.get( partNumber + lotNumber + fabLotNumber );
                            if (inventoryLot == null)
                            {
                                inventoryLot = new InventoryLot( VENDOR_NAME_UTAC_SH, LOCATION_TYPE_FG);
                                m_fgUSCDataMap.put(partNumber + lotNumber + fabLotNumber, inventoryLot);
                            }

                           int quantity = 0;
                            if (inventoryLot.getQtyIn() != null)
                            {
                                try
                                {
                                    quantity = Integer.parseInt(inventoryLot.getQtyIn());
                                }
                                catch (NumberFormatException ignore) {
                                }
                                quantity += result.getInt("Qty");
                            }
                            else
                            {
                                quantity = result.getInt("Qty");
                            }
                            if ( quantity > 0 )
                            {
                                inventoryLot.setPartNumber( partNumber );
                                inventoryLot.setLotNumber( lotNumber );
                                inventoryLot.setFabLotNumber( fabLotNumber );
                                inventoryLot.setDateIn( dateIn );
                                inventoryLot.setStage( result.getString("Stage"));
                                inventoryLot.setQtyIn(quantity+"");
                                inventoryLot.setStatus(lotStatus);
                                inventoryLot.setCategory( lotCategory );
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            System.out.println(" !!ERROR !! ERROR Exception while get getting the UTAC shangai Wip Details");
            e.printStackTrace();
            throw e;

        }
    }

    private void parseDailyUSGWipReport(String fileName) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result        = null;
        AssemblyLot  assemblyLot   = null;
        InventoryLot inventoryLot  = null;
        TestLot      testLot       = null;

        try
        {
            File detailWipFile = new File( fileName );
            if ( !detailWipFile.exists() )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "\nParsing the file for USG Wip Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for USG Wip Report..." );

            Parser parser = ParserFactory.getXLSParser( detailWipFile );

            ArrayList sheetNamesList = ((XLSParserImpl)parser).getSheetNamesList();

            for(int i= 0; i< sheetNamesList.size(); i++ )
            {
                String partNumber       = null;
                String fabLotNumber     = null;
                String lotNumber        = null;

                String sheetName = (String)sheetNamesList.get( i );

                ((XLSParserImpl)parser).setHeaderRowIdx(2);
                ((XLSParserImpl)parser).setDataStartRowIdx(3);
                //System.out.println("sheetName = " + sheetName);
                result = ((XLSParserImpl)parser).parse( sheetName );

                while ( result.next() )
                {
                    partNumber = result.getString("Customer Device");
                    fabLotNumber = result.getString("Customer Lotid");
                    lotNumber = result.getString("Utac Lotid");
                    
                    String lotStatus    = null;
                    String lotCategory  = null;
                    String dateIn       = null;
                    if ( result.getString("Lot Type") != null && "EL".equalsIgnoreCase(result.getString("Lot Type") ) )
                    {
                         lotCategory = LOT_CATEGORY_TYPE_ENGG;
                    }
                    else
                    {
                        lotCategory = LOT_CATEGORY_TYPE_PROD;
                    }
                    if (result.getString("State") != null && ( "HELD".equalsIgnoreCase(result.getString("State") ) || result.getString("State").indexOf("HLD") != -1 ) )
                    {
                        lotStatus = LOT_STATUS_HOLD;
                    }
                    else
                    {
                       lotStatus = LOT_STATUS_RUNNING;
                    }
                    dateIn = DateUtil.getPreviousDate( result.getInt("Lot Age"), "MM/dd/yyyy");

                    if ( partNumber != null && partNumber.trim().length() > 0 && lotNumber != null && lotNumber.trim().length() >0 )
                    {
                        if ( sheetName != null && ( sheetName.toUpperCase().equalsIgnoreCase("ASSY") || sheetName.toUpperCase().equalsIgnoreCase("ASSEMBLY") ) )
                        {
                            if ( result.getString("Stage") != null && "P200-DBANK".equalsIgnoreCase(result.getString("Stage").toUpperCase() ) )
                            {
                                inventoryLot = (InventoryLot)m_dieBankUSGDataMap.get( partNumber + fabLotNumber );
                                if ( inventoryLot == null )
                                {
                                    inventoryLot = new InventoryLot( VENDOR_NAME_UTAC, LOCATION_TYPE_DIE_BANK );
                                    m_dieBankUSGDataMap.put( partNumber + fabLotNumber, inventoryLot );
                                }
                                int quantity = 0;
                                int wquantity = 0;
                                if (inventoryLot.getQtyIn() != null)
                                {
                                    try
                                    {
                                        quantity = Integer.parseInt(inventoryLot.getQtyIn());
                                        wquantity = Integer.parseInt(inventoryLot.getWaferQtyIn());
                                    }
                                    catch (NumberFormatException ignore) {
                                    }
                                    quantity += result.getInt("Qty");
                                    wquantity += result.getInt("Wafer Qty");
                                }
                                else
                                {
                                    quantity = result.getInt("Qty");
                                    wquantity = result.getInt("Wafer Qty");
                                }


                                if (quantity > 0 )
                                {
                                    inventoryLot.setPartNumber( partNumber );
                                    inventoryLot.setLotNumber( fabLotNumber );
                                    inventoryLot.setQtyIn(quantity + "");
                                    inventoryLot.setWaferQtyIn( wquantity + "");
                                    inventoryLot.setDateIn( dateIn );
                                    inventoryLot.setFabLotNumber( fabLotNumber );
                                    inventoryLot.setStatus( lotStatus );
                                    inventoryLot.setLotCategory( lotCategory );
                                }
                            }//End OF Die Bank
                            else
                            {
                                assemblyLot = (AssemblyLot) m_assyUSGWipDataMap.get( partNumber + lotNumber + fabLotNumber );
                                if (assemblyLot == null)
                                {
                                    assemblyLot = new AssemblyLot( VENDOR_NAME_UTAC, WIP_TYPE_ASSEMBLY );
                                    m_assyUSGWipDataMap.put( partNumber + lotNumber + fabLotNumber, assemblyLot);
                                }
                                int quantity = 0;
                                if (assemblyLot.getQtyIn() != null)
                                {
                                    try
                                    {
                                        quantity = Integer.parseInt(assemblyLot.getQtyIn());
                                    }
                                    catch (NumberFormatException ignore) {
                                    }
                                    quantity += result.getInt("Qty");
                                }
                                else
                                {
                                    quantity = result.getInt("Qty");
                                }

                                if ( quantity > 0 )
                                {
                                    assemblyLot.setLotNumber( lotNumber );
                                    assemblyLot.setDeviceName( partNumber );
                                    assemblyLot.setStatus(lotStatus);
                                    assemblyLot.setFabLotNumber( fabLotNumber );
                                    assemblyLot.setCategory( lotCategory );
                                    assemblyLot.setDateIn( dateIn );
                                    assemblyLot.setStage( result.getString("Stage"));
                                    assemblyLot.setQtyIn( quantity+"" );
                                }
                            }
                        } //End Of ASSY Sheet
                        //TEST
                        if ( sheetName != null && sheetName.toUpperCase().equalsIgnoreCase("TEST")  )
                        {
                            testLot = (TestLot) m_ftUSGDataMap.get( partNumber + lotNumber + fabLotNumber );
                            if (testLot == null)
                            {
                                testLot = new TestLot( VENDOR_NAME_UTAC, LOCATION_TYPE_FT );
                                m_ftUSGDataMap.put(partNumber + lotNumber + fabLotNumber, testLot);
                            }

                            int quantity = 0;
                            if (testLot.getQtyIn() != null)
                            {
                                try
                                {
                                    quantity = Integer.parseInt(testLot.getQtyIn());
                                }
                                catch (NumberFormatException ignore) {
                                }
                                quantity += result.getInt("Qty");
                            }
                            else
                            {
                                quantity = result.getInt("Qty");
                            }

                            if ( quantity > 0 )
                            {
                                testLot.setPartNumber( partNumber );
                                testLot.setLotNumber( lotNumber );
                                testLot.setFabLotNumber( fabLotNumber );
                                testLot.setDateIn( dateIn );
                                testLot.setStage( result.getString("Stage") );
                                testLot.setQtyIn( quantity + "");
                                testLot.setStatus(lotStatus);
                                testLot.setCategory( lotCategory );
                            }
                        }//End OF TEST

                        //FG
                        if ( sheetName != null && (sheetName.toUpperCase().equalsIgnoreCase("PTC") || sheetName.toUpperCase().equalsIgnoreCase("EOL") ) )
                        {
                            inventoryLot = (InventoryLot) m_fgUSGDataMap.get( partNumber + lotNumber + fabLotNumber );
                            if (inventoryLot == null)
                            {
                                inventoryLot = new InventoryLot( VENDOR_NAME_UTAC, LOCATION_TYPE_FG);
                                m_fgUSGDataMap.put(partNumber + lotNumber + fabLotNumber, inventoryLot);
                            }

                           int quantity = 0;
                            if (inventoryLot.getQtyIn() != null)
                            {
                                try
                                {
                                    quantity = Integer.parseInt(inventoryLot.getQtyIn());
                                }
                                catch (NumberFormatException ignore) {
                                }
                                quantity += result.getInt("Qty");
                            }
                            else
                            {
                                quantity = result.getInt("Qty");
                            }
                            if ( quantity > 0 )
                            {
                                inventoryLot.setPartNumber( partNumber );
                                inventoryLot.setLotNumber( lotNumber );
                                inventoryLot.setFabLotNumber( fabLotNumber );
                                inventoryLot.setDateIn( dateIn );
                                inventoryLot.setStage( result.getString("Stage"));
                                inventoryLot.setQtyIn(quantity+"");
                                inventoryLot.setStatus(lotStatus);
                                inventoryLot.setCategory( lotCategory );
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            System.out.println(" !!ERROR !! ERROR Exception while get getting the UTAC SG Wip Details");
            e.printStackTrace();
            throw e;

        }
   }
   private static void log( String message )
   {

        if ( message == null ) return;

        if ( m_parserLogger != null )
        {
            synchronized ( m_parserLogger )
            {
                m_parserLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}

